package com.yzt.zhuju.gift;

import android.animation.AnimatorSet;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.yzt.zhuju.IService.message.IMessageService;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.gift.GiftComboFinishEvent;
import com.yzt.zhuju.event.gift.UpdateDiamondEvent;
import com.yzt.zhuju.event.gift.UpdatePacketNumEvent;
import com.yzt.zhuju.event.gift.UpdateUbiEvent;
import com.yzt.zhuju.event.main.SendGiftSuccessEvent;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.chatroom.GiftIconEvent;
import com.yzt.zhuju.network.entity.gift.Gift;
import com.yzt.zhuju.network.entity.gift.GiftBatterInfo;
import com.yzt.zhuju.network.entity.gift.GiftListResponse;
import com.yzt.zhuju.network.entity.gift.GiftResponse;
import com.yzt.zhuju.network.entity.gift.SelfSendGiftInfo;
import com.yzt.zhuju.network.entity.gift.SendGiftRequest;
import com.yzt.zhuju.network.entity.gift.SendGiftResult;
import com.yzt.zhuju.network.entity.mine.wallet.WalletBean;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.p_base.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Describe:  礼物连击倒计时管理类
 */
public class GiftBatterManager {

    private static GiftBatterManager mInstance;

    private final Map<Integer, GiftBatterInfo> TimeMap = new HashMap<>();
    private final Map<Integer, CountDownTimer> countDownTimerMap = new HashMap<>();
    private List<GiftListResponse> ubiPackGiftList = new ArrayList<>(); //U币背包
    private List<GiftListResponse> packGiftList = new ArrayList<>(); //钻石背包
    private double diamondNum = 0;
    private double ubiNUm = 0;
    private double activityUbiNum = 0;
    private SelfSendGiftInfo newInfo;
    private AnimatorSet progressAnimation;
    private SelfSendGiftInfo newUbiInfo;
    private List<SendGiftPerson> sendGiftPersonList = new ArrayList<>();

    private GiftBatterManager() {

    }

    public void destroyDiamond() {
        packGiftList.clear();
        diamondNum = 0;
    }

    public void clearSendGiftPersonList() {
        sendGiftPersonList.clear();
    }

    public void destroyUbi() {
        ubiPackGiftList.clear();
        ubiNUm = 0;
    }

    public static GiftBatterManager getInstance() {
        if (mInstance == null) {
            synchronized (GiftBatterManager.class) {
                if (mInstance == null) {
                    mInstance = new GiftBatterManager();
                }
            }
        }
        return mInstance;
    }

    public void startCountdown(GiftBatterInfo giftBatter, SelfSendGiftInfo giftInfo, String roomId) {
        if (countDownTimerMap.containsKey(giftBatter.getGiftId())) {
            countDownTimerMap.get(giftBatter.getGiftId()).cancel();
            countDownTimerMap.remove(giftBatter.getGiftId());
        }
        CountDownTimer countDownTimer = new CountDownTimer(giftBatter.getTime(), 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                giftBatter.setTime(millisUntilFinished);
                TimeMap.put(giftBatter.getGiftId(), giftBatter);
            }

            @Override
            public void onFinish() {
                TimeMap.remove(giftBatter.getGiftId());
                countDownTimerMap.remove(giftBatter.getGiftId());
                giftInfo.setGiftNum(giftBatter.getNumber());
                if (TextUtils.isEmpty(roomId)) {
                    if (giftInfo.getTypeId() == 1398) {
//                        if (!giftInfo.getList().get(0).equals(RXingUtils.getUserId())) {
//                            String text = giftInfo.getGiftName() + "x" + giftInfo.getGiftNum();
//                            IMessageService messageService = ARouter.getInstance().navigation(IMessageService.class);
//                            messageService.sendGiftMessageToOne(giftInfo.getList().get(0), text, giftInfo.getGiftIcon());
//                            org.greenrobot.eventbus.EventBus.getDefault().post(new GiftIconEvent());
//                        }
                    } else {
                        sendComboUbiGift(giftInfo);
                    }
                    return;
                }
                RxBus.getDefault().post(new GiftComboFinishEvent(giftInfo, roomId));
            }
        };
        countDownTimer.start();
        TimeMap.put(giftBatter.getGiftId(), giftBatter);
        countDownTimerMap.put(giftBatter.getGiftId(), countDownTimer);
    }

    public void updateSendNum(GiftBatterInfo batter) {
        TimeMap.put(batter.getGiftId(), batter);
    }

    public GiftBatterInfo getTimeByGiftId(int giftId) {
        if (TimeMap.containsKey(giftId)) {
            return TimeMap.get(giftId);
        }
        return null;
    }

    /**
     * 更新钻石数据
     */
    private void updateWalletInfo() {
        BizLayer.getInstance().getMineModule().wallet( new AresSubscriber<WalletBean>() {
            @Override
            protected void onSuccess(WalletBean walletEntry) {
                setDiamondNum(walletEntry.getCandyNum());
            }
        });
    }

    public double getActivityUbiNum() {
        return activityUbiNum;
    }

    public void setActivityUbiNum(double activityUbiNum) {
        this.activityUbiNum = activityUbiNum;
    }

    public void initDiamond() {
        updateWalletInfo();
    }

    public List<GiftListResponse> getUbiPackGiftList() {
        return ubiPackGiftList;
    }

    public void setUbiPackGiftList(List<GiftListResponse> ubiPackGiftList) {
        this.ubiPackGiftList = ubiPackGiftList;
    }

    public List<GiftListResponse> getPackGiftList() {
        return packGiftList;
    }

    public void setPackGiftList(List<GiftListResponse> packGiftList) {
        this.packGiftList = packGiftList;
    }

    public double getDiamondNum() {
        return diamondNum;
    }

    public void setDiamondNum(double diamondNum) {
        this.diamondNum = diamondNum;
        RxBus.getDefault().post(new UpdateDiamondEvent());
    }

    public double getUbiNUm() {
        return ubiNUm;
    }

    public void setUbiNUm(double ubiNUm) {
        this.ubiNUm = ubiNUm;
        RxBus.getDefault().post(new UpdateUbiEvent());
    }

    public Gift getGiftById(List<GiftListResponse> list, int id) {
        int[] selectIndex = GiftManager.getInstance().getSelectIndex();
        List<Integer> tabId = GiftManager.getInstance().getTabId();
        if (tabId == null || tabId.size() <= selectIndex[1]) {
            return null;
        }
        for (GiftListResponse giftResponse : list) {
            if (selectIndex[1] != -1 && tabId.get(selectIndex[1]) != giftResponse.getId()) {
                continue;
            }
            for (Gift gift : giftResponse.getList()) {
                if (id == gift.getGift()) {
                    return gift;
                }
            }
        }
        return null;
    }

    public void updatePackGiftCountById(List<GiftListResponse> list, int id, int count) {
        boolean isFind = false;
        int[] selectIndex = GiftManager.getInstance().getSelectIndex();
        List<Integer> tabId = GiftManager.getInstance().getTabId();
        if (tabId == null || tabId.size() <= selectIndex[1]) {
            return;
        }
        for (GiftListResponse giftResponse : list) {
            if (selectIndex[1] != -1 && tabId.get(selectIndex[1]) != giftResponse.getId()) {
                continue;
            }
            for (Gift gift : giftResponse.getList()) {
                if (id == gift.getGift()) {
                    int total = gift.getCounts();
                    if (count > total) {
                        ToastUtil.showMessage("您的礼物数量不足");
                        return;
                    }
                    gift.setCounts(total - count);
                    RxBus.getDefault().post(new UpdatePacketNumEvent(gift));
                    isFind = true;
                    break;
                }
            }
            if (isFind) {
                break;
            }
        }
    }

    public void setNewInfo(SelfSendGiftInfo newInfo) {
        this.newInfo = newInfo;
    }

    public SelfSendGiftInfo getNewInfo() {
        return newInfo;
    }

    public List<SendGiftPerson> getSendGiftPersonList() {
        return sendGiftPersonList;
    }

    public AnimatorSet getProgressAnimator() {
        return progressAnimation;
    }

    public void setProgressAnimator(AnimatorSet progressAnimator) {
        this.progressAnimation = progressAnimator;
    }

    public void setSendGiftPersonList(List<SendGiftPerson> sendGiftPersonList) {
        this.sendGiftPersonList = sendGiftPersonList;
    }

    public SelfSendGiftInfo getNewUbiInfo() {
        return newUbiInfo;
    }

    public void setNewUbiInfo(SelfSendGiftInfo newUbiInfo) {
        this.newUbiInfo = newUbiInfo;
    }


    /**
     * 赠送U币连击礼物
     */
    public void sendComboUbiGift(SelfSendGiftInfo info) {
        SendGiftRequest mSendGiftRequest = new SendGiftRequest();
        mSendGiftRequest.setAmount(String.valueOf(info.getGiftId()));
        mSendGiftRequest.setIncomeUid(info.getList().get(0));
        mSendGiftRequest.setNum(info.getGiftNum());
        mSendGiftRequest.setIsWareHouse(info.getIsWareHouse());
        mSendGiftRequest.setTabId(info.getTabId());
//        BizLayer.getInstance().getGiftModule().postSendGiftToOther(mSendGiftRequest, new AresSubscriber<SendGiftResult>() {
//            @Override
//            protected void onSuccess(SendGiftResult response) {
//                updateMessage(response, info);
//                RxBus.getDefault().post(new SendGiftSuccessEvent(info.getGiftId()));
//            }
//
//            @Override
//            protected void onError(int code, String i) {
//                super.onError(code, i);
//                //送u币礼物u币不足
//            }
//        });
    }

    /**
     * 发送礼物消息
     * 播放礼物动画
     */
    private void updateMessage(SendGiftResult response, SelfSendGiftInfo info) {

        if (response.getIsStopSendMessage() != 1) {
            if (!info.getList().get(0).equals(RXingUtils.getUserId())) {
                String text = response.getData().getGift() + "x" + response.getData().getNum();
                IMessageService messageService = ARouter.getInstance().navigation(IMessageService.class);
                messageService.sendGiftMessageToOne(info.getList().get(0), text, response.getData().getIcon());

                org.greenrobot.eventbus.EventBus.getDefault().post(new GiftIconEvent());
            }
        }
        if (response.getData() != null && !TextUtils.isEmpty(response.getData().getMp4())) {
            GiftAnimShowDialog giftAnimDialogFragment = (GiftAnimShowDialog) GiftAnimShowDialog.showDialog(ActivityManagerUtils.getInstance().getTopActivity(), GiftAnimShowDialog.class);
            if (giftAnimDialogFragment != null) {
                giftAnimDialogFragment.setCancelable(false);
                Bundle data = new Bundle();
                data.putString("alphaVideoUrl", response.getData().getMp4());
                data.putString("giftName", info.getGiftName());
                data.putString("sound_file", response.getData().getSound_file());
                giftAnimDialogFragment.setArguments(data);
            }
        } else if (!TextUtils.isEmpty(info.getPath())) {
            GiftAnimShowDialog giftAnimDialogFragment = (GiftAnimShowDialog) GiftAnimShowDialog.showDialog(ActivityManagerUtils.getInstance().getTopActivity(), GiftAnimShowDialog.class);
            if (giftAnimDialogFragment != null) {
                giftAnimDialogFragment.setCancelable(false);
                Bundle data = new Bundle();
                if (info.getPathType() == 2) {
                    data.putString("gifGiftUrl", info.getPath());
                } else if (info.getPathType() == 1) {
                    data.putString("svgaImage", response.getData().getSvgaImage());
                }
                data.putString("giftName", info.getGiftName());
                data.putString("svgaConfig", response.getData().getSvgaConfig());
                data.putString("sound_file", response.getData().getSound_file());
                giftAnimDialogFragment.setArguments(data);
            }
        }
    }
}
